const express = require('express');
const userModel = require('../middlewares/dbconf/userModel');
const listModel = require('../middlewares/dbconf/listModel');
const verify = require('../middlewares/verify');
const router = express.Router();

//处理注册业务
router.post('/register',(req,res) => {
    userModel.create(req.body);
    req.session.username = req.body.username;
    res.redirect('/countDown-center');
});

//处理登录业务
router.post('/login',(req,res) => {
    const {username,pwd} = req.body;
    userModel.find({username,pwd}).then((value) => {
        if(value.length){
            req.session.username = username;
            res.redirect('/');
        }else{
            res.redirect('/login');
        }
    });
});

//处理退出登录
router.get('/logout',(req,res) => {
    req.session.destroy();
    res.redirect('/countDown-login');
});

//响应当前登录用户名
router.get('/getUserName',(req,res) => {
   res.send(req.session.username);
});

//处理获取列表
router.get('/getList',(req,res) => {
    listModel.find({username:req.session.username}).then((value) => {
        res.json(value);
    });
});

//添加列表数据
router.post('/add',(req,res) => {
    listModel.create(req.body);
    res.redirect('/');
});

//编辑时先获取该条数据
router.get('/getEdit',(req,res) => {
    listModel.find({_id:req.query.id}).then((value) => {
        res.json(value);
    });
});

//编辑完成，修改数据
router.post('/edit',(req,res) => {
    listModel.updateOne({_id:req.body.id},req.body).then((value) => {
        res.redirect('/');
    });
});

//删除列表
router.get('/del',verify,(req,res) => {
    listModel.deleteOne({_id:req.query.id}).then((value) => {
        res.redirect('/');
    });
});


module.exports = router;